<template>
    <rx-layout>
        <template v-slot:center>
            <!--指定人员-->
            <div v-if="assignFlowUsers" class="bpm-view">
                <div class="bpm-view-name">{{i18n('designated','指定人员')}}</div>
                <div v-for="reqNode in startReqNodes">
                    <div style="margin-top: 15px"> {{ reqNode.nodeName }}</div>
                    <RxVueUserDialog v-model="reqNode.users"
                                     :organization="true"></RxVueUserDialog>
                </div>
            </div>
            <div v-if="batchNodes.length>0" class="bpm-view">
                <div class="bpm-view-name">{{i18n('designatedNode','指定批次节点人员')}}</div>
                <div v-for="batchNode in batchNodes">
                    <div style="margin-top:0.5rem">{{ batchNode.nodeName }}</div>
                    <div style="margin-top: 0.5rem" v-for="(batch,index) in batchNode.batchGroups">
                        <div class="bpm-header-toolbar">
                            <div style="flex: 1">
                                <input v-if="batch.isNew" v-model="batch.name" :placeholder="i18n('isNew','请输入批次名称') "/>
                                <span v-else>{{ batch.name }}</span>
                            </div>
                            <div class="bpm-toolbar-right">
                                <div class="bpm-toolbar-right-select">
                                    <div v-if="batch.isNew">
                                        <next-data-select style="width: 100px" v-model="batch.executeType"
                                                          optionsValueKey="value" optionsLabelKey="label"
                                                          :options="executeOptions"></next-data-select>
                                    </div>
                                    <span v-else>{{ executeTypeMap[batch.executeType].text }}</span>
                                </div>
                                <my-icon v-if="batchNode.batchOptions.includes('allowDel')"
                                         style="cursor: pointer;color:red;"
                                         @click="removeBatch(batchNode,index)" type="icon-Vue3_delete"></my-icon>
                            </div>
                        </div>
                        <RxVueUserDialog v-model="batch.users"
                                         :organization="true"></RxVueUserDialog>
                    </div>
                    <div class="bpm-add-button-content" v-if="batchNode.batchOptions.includes('allowAdd')" @click="addBatch(batchNode)">{{i18n('allowAdd','新增批次')}}</div>
                </div>
            </div>
            <div class="bpm-direction" v-if="processConfig.allowSelectPath">
                <div class="bpm-view-name " style="padding-left: 10px;margin-bottom: 15px">{{i18n('nodeExecutors','即将流向')}}</div>
                <bpm-task-executors ref="taskExecutors" :nodeExecutors="nodeExecutors"></bpm-task-executors>
            </div>
            <div class="bpm-view" style="margin-top: 15px" v-if="fillOpinion==true">
                <div class="bpm-view-name">{{i18n('instructions','提交说明')}}</div>
                <textarea class="bpm-view-textarea" :placeholder="i18n('instructionsOpinion','请输入提交说明')" v-model="opinion"/>
            </div>
        </template>
        <template v-slot:footer>
            <div class="bpm-footer">
                <div @click="closeWindow" class="bpm-footer-close">{{i18n('close','取消')}}</div>
                <div @click="submitForm" class="bpm-footer-ok">{{i18n('ok','确定')}}</div>
            </div>
        </template>
    </rx-layout>
</template>

<script>
import RxVueUserDialog from '@/components/RxVueUserDialog';
import RxLayout from '@/components/RxLayout'
import BpmDefApi from "@/api/rxBpm/bpmDef"
import BpmTaskExecutors from './BpmTaskExecutors'
import BpmInstApi from "@/api/rxBpm/bpmInst";

export default {
    name: "BpmInstStartConfirm",
    components: {
        RxVueUserDialog,
        RxLayout,
        BpmTaskExecutors
    },
    props:['appId'],
    data() {
        return {
            /**
             * 表单方案别名
             */
            formSolutionAlias: '',
            /**
             * 流程全局配置
             */
            processConfig: {required: true},
            /**
             * 流程定义ID
             */
            defId: '',
            /**
             * 流程实例ID
             */
            instId: '',
            /**
             * 表单数据
             */
            formData: {},
            //定义数据
            //填写意见
            fillOpinion: false,
            //配置后续用户
            assignFlowUsers: false,
            //计算后续执行用户
            startCalFlowusers: false,
            //是否显示指定关联流程
            showRelInsts: false,
            batchNodes: [],//批次节点
            startReqNodes: [],//必填节点项
            nodeUsers: [],//后续节点人员Id列表,
            nodeExecutors: [],
            fileList: [],
            relInsts: [],
            opinion: "",
            executeOptions: [
                {value: "normal", label:this.i18n('normal','抢签')},
                {value: "parallel", label:this.i18n('parallel','并行')},
                {value: "sequential", label:this.i18n('sequential','串行')}
            ],
            executeTypeMap: {
                normal: {color: "orange", text: this.i18n('normal','抢签')},
                parallel: {color: "blue", text: this.i18n('parallel','并行')},
                sequential: {color: "green", text: this.i18n('sequential','串行')}
            },
        }
    },
    onLoad(option) {
        let BpmInstStartConfirm = uni.getStorageSync('BpmInstStartConfirm')
        let optionData = JSON.parse(BpmInstStartConfirm);
        this.formSolutionAlias = optionData.formSolutionAlias;
        this.defId = optionData.defId;
        this.instId = optionData.instId;
        this.formData = optionData.formData;
        this.processConfig = optionData.processConfig;
    },
    methods: {
        i18n(name,text,key){
            return this.$ti18(name,text,"bpmTaskLang.BpmInstStartConfirm",key);
        },
        addBatch(batchNode) {
            batchNode.batchGroups.push({
                isNew: true,
                name: "",
                executeType: "normal",
                condition: "",
                allowSelectUser: true,
                users: []
            });
        },
        removeBatch(batchNode, index) {
            batchNode.batchGroups.splice(index, 1);
        },
        closeWindow() {
            uni.navigateBack({
                delta: 1
            })
        },
        async submitForm() {
            this.loading = true
            let self = this;
            var objNodeUsers = this.getNodeUsers();
            if (!objNodeUsers.isNodeUserSet) {
                uni.showToast({
                    title:this.i18n('isNodeUserSet','必填节点没有选择人员！'), // 消息内容
                    duration: 2000, // 持续时间（单位：毫秒）
                    icon: 'none' // 图标类型（可选值：success/loading/none）
                });
                return;
            }
            //获取当前需要提交的数据。
            var result = this.getSubmitData(objNodeUsers);
            if (!result.success) {
                self.loading = false;
                return;
            }
            BpmInstApi.startProcess(result.data).then(data => {
                if (data.success) {
                    uni.showToast({
                        title:this.i18n('startProcess','启动流程成功'), // 消息内容
                        duration: 2000, // 持续时间（单位：毫秒）
                        icon: 'none' // 图标类型（可选值：success/loading/none）
                    });
                    uni.navigateBack({
                        delta: 2
                    })
                } else {
                    uni.showToast({
                        title:this.i18n('startNo','启动流程失败'), // 消息内容
                        duration: 2000, // 持续时间（单位：毫秒）
                        icon: 'none' // 图标类型（可选值：success/loading/none）
                    });
                }
            })
        },
        getNodeUsers() {
            let nodeUserIds = {};
            //节点人员是否设置了
            let isNodeUserSet = true;
            //检查是否有存在的节点人员必须需要
            if (this.assignFlowUsers) {
                for (let i = 0; i < this.startReqNodes.length; i++) {
                    var node = this.startReqNodes[i];
                    if (node.users.length == 0) {
                        isNodeUserSet = false;
                        break;
                    }
                    let userIds = [];
                    node.users.forEach(item => {
                        userIds.push(item.id);
                    });
                    nodeUserIds[node.nodeId] = userIds.join(',');
                }

            }
            return {nodeUserIds: nodeUserIds, isNodeUserSet: isNodeUserSet};
        },
        getSubmitData(objNodeUsers) {
            let data = this.getFormData();
            data.checkType = "AGREE";
            data.opFiles = JSON.stringify(this.fileList);
            data.relInsts = JSON.stringify(this.relInsts);
            data.opinion = this.opinion;
            //是否已有主键。
            var hasPk = this.processConfig.hasPk;
            if (hasPk) {
                data.systemHand = true;
                data.hasPk = true;
            }

            if (this.processConfig.assignBatchFlowUsers) {
                let batchNodeGroups = {};
                for (let i = 0; i < this.batchNodes.length; i++) {
                    var node = this.batchNodes[i];
                    if (!node.allowExecutorNull && (node.batchGroups.length == 0 || node.batchGroups[0].users.length == 0)) {
                        uni.showToast({
                            title:this.i18n('allowExecutorNull','批次节点必须配置批次组人员！'), // 消息内容
                            duration: 2000, // 持续时间（单位：毫秒）
                            icon: 'none' // 图标类型（可选值：success/loading/none）
                        });
                        return {success: false};
                    }
                    batchNodeGroups[node.nodeId] = node.batchGroups;
                }
                data["batchNodeGroups"] = JSON.stringify(batchNodeGroups);
            }
            data.nodeUserIds = JSON.stringify(objNodeUsers.nodeUserIds);
            //选择执行路径
            if (this.processConfig.allowSelectPath) {
                var ctlUsers = this.$refs.taskExecutors;
                var destNodeId = ctlUsers.getDestNodeId();
                var userMap = ctlUsers.getNodeUserMap();
                data.nodeExecutors = userMap;
                data.destNodeId = destNodeId;
            }
            if (this.instId) {
                data.instId = this.instId;
            }
            return {success: true, data: data};
        },
        getFormData() {
            let data = {defId: this.defId,isMobile: 'YES'};
            let formJson = JSON.stringify(this.formData);
            data.formJson = formJson;
            if (this.instId) {
                data.instId = this.instId;
            }
            data.formSolutionAlias = this.formSolutionAlias;
            return data;
        },
        getStartUserNodes() {
            let self = this;
            //传入 defId 则可
            var formData = this.getFormData().formJson;

            BpmDefApi.getStartUserNodes(this.defId, formData).then(resp => {
                self.startReqNodes = [];
                resp.forEach(item => {
                    self.startReqNodes.push({
                        nodeId: item.nodeId,
                        nodeName: item.name,
                        users: item.users,
                        single: item.singleExecutor,
                        allowSelectExecutor: item.allowSelectExecutor
                    });
                });
            });
        },
        getFlowNodesExecutors() {
            //传入 defId 则可
            var formData = this.getFormData().formJson;
            BpmDefApi.getFlowNodesExecutors(this.defId, formData).then(res => {
                for (var i = 0; i < res.length; i++) {
                    var o = res[i];
                    o.selected = i == 0;
                }
                this.nodeExecutors = res;
            })
        },
        getBatchUserNodes() {
            let self = this;
            //传入 defId 则可
            var formData = this.getFormData().formJson;

            BpmDefApi.getBatchUserNodes(this.defId, formData).then(resp => {
                self.batchNodes = [];
                resp.forEach(item => {
                    let {options, groups} = item.batchGroup;
                    self.batchNodes.push({
                        nodeId: item.nodeId,
                        nodeName: item.name,
                        allowExecutorNull: item.allowExecutorNull,
                        i18nJson: item.i18nJson,
                        batchOptions: options || [],
                        batchGroups: groups || []
                    });
                });
            });
        },
    },
    watch: {
        batchNodes: {
            handler(newVal) {
                if (!newVal) {
                    return;
                }
                let batchNodeMap = {};
                newVal.forEach(item => {
                    if (item.batchGroups && item.batchGroups.length > 0) {
                        batchNodeMap[item.nodeId] = item.batchGroups[0].users;
                    } else {
                        batchNodeMap[item.nodeId] = [];
                    }
                })
                for (let i = 0; i < this.nodeExecutors.length; i++) {
                    let node = this.nodeExecutors[i];
                    let nodeUsers = batchNodeMap[node.nodeId];
                    if (nodeUsers) {
                        node.executors = nodeUsers;
                    }
                }
            },
            deep: true
        },
        processConfig: {
            handler(newVal, oldVal) {
                if (!newVal) {
                    return;
                }
                this.buttons = newVal.buttons;
                if (newVal.startNodeOptions instanceof Array) {
                    this.startConfirm = newVal.startNodeOptions.indexOf('startConfirm') != -1;
                    this.fillOpinion = newVal.startNodeOptions.indexOf('fillOpinion') != -1;
                    //执行下一步用户。
                    this.assignFlowUsers = newVal.startNodeOptions.indexOf('assignFlowUsers') != -1;
                    this.startCalFlowusers = newVal.startNodeOptions.indexOf('startCalFlowusers') != -1;
                    this.showRelInsts = newVal.startNodeOptions.indexOf('relInsts') != -1;

                }
                //是否需要显示弹出的窗口
                if (this.assignFlowUsers) {
                    this.getStartUserNodes();
                }
                if (newVal.allowSelectPath) {
                    this.getFlowNodesExecutors();
                }
                if (newVal.assignBatchFlowUsers) {
                    this.getBatchUserNodes();
                }

            },
            immediate: true
        },
    }
}
</script>

<style scoped>
.bpm-add-button-content{
    height: 2rem;
    border-radius: 8px;
    background: rgba(66, 133, 244, 1);
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 15px;
    color: white;
    margin-top: 0.5rem;
}
.bpm-header-toolbar{
    display: flex;
    align-items: center;
    margin-bottom: 0.5rem;
}
.bpm-toolbar-right{
    display: flex;
    align-items: center;
}
.bpm-toolbar-right-select{
    margin-right: 0.5rem;
}
.bpm-direction {
    background: white;
    border-radius: 8px;
    padding-top: 12px;
    box-sizing: border-box;
    margin-top: 10px;
    box-sizing: border-box;
    overflow: hidden;
}

.bpm-direction-name {
    font-size: 0.8rem;
    font-weight: 700;
    letter-spacing: 0px;
    line-height: 21px;
    display: block;
    color: rgba(0, 0, 0, 0.85);
    padding: 0px 12px;
    padding-bottom: 15px;
    border-bottom: 1px solid rgba(232, 232, 232, 1);
}

.bpm-view {
    background: white;
    border-radius: 8px;
    padding: 12px;
    box-sizing: border-box;
}

.bpm-view-name {
    line-height: 21px;
    color: rgba(0, 0, 0, 0.85);
}

.bpm-footer {
    display: flex;
    grid-gap: 10px;
}

.bpm-footer-close {
    flex: 1;
    height: 45px;
    opacity: 1;
    border-radius: 8px;
    background: rgba(255, 255, 255, 1);
    border: 1px solid rgba(232, 232, 232, 1);
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 15px;
    color: rgba(0, 0, 0, 0.65);
}

.bpm-footer-ok {
    flex: 1;
    height: 45px;
    opacity: 1;
    border-radius: 8px;
    background: rgba(66, 133, 244, 1);
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 15px;
    color: white;
}
</style>
